#include "stdio.h"
#include "stdlib.h"
#include "assert.h"
#include "GABoard.h"


GABoard::GABoard(int nWidth, int nHeight)
{
	m_nWidth = nWidth;
	m_nHeight = nHeight;
	m_pBoard = new GAPiece[nWidth * nHeight];
	assert(m_pBoard != NULL);
	Clear();
}

GABoard::~GABoard()
{
	delete[] m_pBoard;
}

GAPiece& GABoard::PieceAt(int x, int y)
{
	return m_pBoard[y * m_nWidth + x];
}


void GABoard::Clear(void)
{
	int x,y;
	for(y = 0; y < m_nHeight; y++)
	{
		for(x = 0; x < m_nWidth; x++)
		{
			m_pBoard[y * m_nWidth + x].nFlags = FLAG_OFF;
		}
	}
}
void GABoard::RemoveOneLine(int y)
{
	while(y > 0)
	{
		int x = 0;
		while(x < m_nWidth)
		{
			m_pBoard[y * m_nWidth + x] = m_pBoard[(y - 1) * m_nWidth + x];
			x++;
		}
	}
}

int GABoard::ApplyGravity(void)
{
	int x,y;
	int nJumpLine = 0;
	int *pLineFlag = new int[m_nHeight];
	assert(pLineFlag != NULL);

	for(y = m_nHeight - 1; y >= 0; y--)
	{
		for(x = 0; x < m_nWidth; x++)
		{
			if(!IsPieceOn(x,y))
				break;
		}

		if(x >= m_nWidth)
		{
			pLineFlag[y] = 1; //full line
		}
		else
			pLineFlag[y] = 0;
	}

	for(y = m_nHeight - 1; y >= 0; y--)
	{
		if(pLineFlag[y] == 1)
		{
			nJumpLine ++;
			continue;
		}

		if(nJumpLine < 1)
			continue;
		for(x = 0; x < m_nWidth; x++)
		{
			m_pBoard[(y + nJumpLine) * m_nWidth + x].nFlags = m_pBoard[y * m_nWidth + x].nFlags;
			m_pBoard[y * m_nWidth + x].nFlags = FLAG_OFF;
		}
	}

	delete[] pLineFlag;
	return nJumpLine;
}


